package com.suxin.tomcat;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author Tang
 * @classname SocketBufferHandler
 * @description [  ]
 * @date 2021/7/7 9:49
 */
public class SocketBufferHandler {

    private ByteBuffer readBuffer;
    private byte[] readBytes;
    private ByteBuffer writerBuffer;

    public SocketBufferHandler(int readBufferSize,int writerBufferSize) {
        readBuffer = ByteBuffer.allocate(readBufferSize);
        readBytes = new byte[readBufferSize];
        writerBuffer = ByteBuffer.allocate(writerBufferSize);
    }

    public String readDate(SocketChannel socket) {
        try {
            int readLen = 0;
            while ((readLen = socket.read(readBuffer)) > 0){
                readBuffer.flip();
                byte[] tempBytes = new String(readBuffer.array(), 0, readLen).getBytes();
                byte[] newBytes = new byte[readBytes.length + 1024];
                System.arraycopy(tempBytes, 0, newBytes, 0, tempBytes.length);
                readBytes = newBytes;
                readBuffer.clear();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String result = new String(readBytes);
        readBytes = new byte[readBuffer.capacity()];
        return result;
    }

}